#!/usr/bin/python3
# -*- coding: utf-8 -*-

"""
@Time        : 2020/4/24
@Author      : dreamhomes
@File        : china_weather
@Description : 获取中国天气网信息
"""
import requests
import re
import json
from datetime import datetime, timedelta
from lunardate import LunarDate

import os
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.header import Header
import argparse
import time
import pytz

def send_mail(**mail):
    """
    发送邮件， mail为以下字段
    server | port | FROM | password | subject | to | content | attachment |
    """

    server = mail.get('server', '')
    port = mail.get('port', 465)
    FROM = mail.get('FROM', '')
    password = mail.get('password', '')
    subject = mail.get('subject', '')
    receiver = mail.get('to', [])
    content = mail.get('content', '')
    attachment = mail.get('attachment', [])

    if (not all([server, FROM, password, receiver])):
        print("invalid argument", mail)
        exit(1)

    msg = MIMEMultipart()
    msg['Subject'] = Header(subject, 'utf-8')
    msg['From'] = 'server<%s>' %FROM
    msg['To'] = ';'.join(receiver)
    msg.attach(MIMEText(content, 'plain', 'utf-8'))

    #add attachment
    for path in attachment:
        if not os.path.isfile(path):
            continue
        attachment = MIMEApplication(open(path, 'rb').read())
        attachment.add_header('Content-Disposition', 'attachment', filename='{0}'.format(os.path.basename(path)))
        msg.attach(attachment)

        #TODO(xcy): delete file ?
        #del_file and os.remove(path)

    try:
        #smtp = smtplib.SMTP()
        #smtp.connect(server)
        smtp = smtplib.SMTP_SSL(server, port)
        smtp.login(FROM, password)
        smtp.sendmail(FROM, receiver, msg.as_string())
    except Exception as e:
        print("send mail to %s error!" % ";".join(receiver))
        print(e)
        return False

    smtp.quit()

    return True



def get_information(html):
    """
    Get More Weather Information.
    Arguments:
        html {String} -- location html

    Returns:
        String -- Information
    """
    #print(html)
    response = requests.get(html)
    content = response.content.decode("utf-8")
    #print(content[:30000])
    city = re.findall(
        #r'target="_blank">全国</a><span>&gt;</span>(\s+)<a>(.*?)</a>(\s+)<span>></span>(\s+)<span>(.*?)</span>',
        r'target="_blank">全国</a><span>&gt;</span>(\s+)<a>(.*?)</a>(\s+)<span>></span>(\s+.*?)<span>(.*?)</span>',
        #r'>当前城市：<span>(.*?)<img(.*?)</span>(\s+)<div id="select">(\s+)<span>(.*?)</span>',
        content)
    aim = re.findall(
        r'<input type="hidden" id="hidden_title" value="(.*?)月(.*?)日(.*?)时(.*?) (.*?)  (.*?)  (.*?)"',
        content)
    air_data = re.findall(
        r'</i>\n<span>(.*?)</span>\n<em(.*?)>(.*?)</em>\n<p>(.*?)</p>\n</li>\n<li>',
        content)
    ult_index = re.findall(
        r'<li class="li1 hot">\n<i></i>\n<span>(.*?)</span>\n<em>(.*?)</em>\n<p>(.*?)</p>\n</li>',
        content)
    cloth_index = re.findall(
        r'<i></i>\n<span>(.*?)</span>\n<em>(.*?)</em>\n<p>(.*?)</p>\n</a>\n</li>\n<li class="li4 hot dazhong">',
        content)
    # wash_index = re.findall(r'<li class="li4">\n<i></i>\n<span>(.*?)</span>\n<em>(.*?)</em>\n<p>(.*?)</p>', content)
    lose_index = re.findall(
        r'<span>(.*?)</span>\n<em>(.*?)</em>\n<p>(.*?)</p>\n</li>\n<li class="li16">',
        content)
    print(city)
    #print(cloth_index)
    data = {}
    data['city'] = city[0][1].strip() + '-' + city[0][4]
    data['weather'] = aim[0][5]
    data['temp'] = aim[0][6]
    data['wear'] = cloth_index[0][0] + '，' + cloth_index[0][2]
    data['sport'] = lose_index[0][0] + '，' + lose_index[0][2]
    data['feeling'] = air_data[0][0] + '，' + air_data[0][3]
    data['sun'] = ult_index[0][0] + '，' + ult_index[0][2]
    return data

def get_daily_sentence():
    """
    Get  AiCiBa Daily Sentence
    return: string English + Chinese
    """
    url = 'http://open.iciba.com/dsapi/'
    r = requests.get(url)
    text = json.loads(r.text)
    english = text['content']
    chinese = text['note']
    daily_sentence = '\n@每日壹句:' + '\n' + english + '\n' + chinese + '\n'
    return daily_sentence

def get_daily_love():
    """
    每日情话
    :return: string
    """
    url = "https://api.lovelive.tools/api/SweetNothings/Serialization/Json"
    r = requests.get(url)
    all_dict = json.loads(r.text)
    sentence = all_dict['returnObj'][0]
    return sentence
    #daily_love = '\n@每日情话:' + '\n' + sentence + '\n'
    #return daily_love

def get_daily_love2():
    """
    每日情话
    :return: string
    """
    url = "https://api.vvhan.com/api/love?type=json"
    r = requests.get(url)
    all_dict = json.loads(r.text)
    # print (all_dict)
    sentence = all_dict['ishan']
    return sentence

def count_day(start_time):
    '''
    计算隔多少天
    '''
    date_now = datetime.now(pytz.timezone('PRC'))
    date_before = datetime.strptime(start_time, '%Y-%m-%d')
    dt_before = pytz.timezone("PRC").localize(date_before)
    return (date_now - dt_before).days + 1

def count_birthday(month, day):
    '''
    计算生日还有多少天
    '''
    date_now = datetime.now().date()
    year = date_now.year
    lunar_date = LunarDate(year, month, day)
    solar_date = lunar_date.toSolarDate()
    if date_now > solar_date:
        lunar_date = LunarDate(year + 1, month, day)
        solar_date = lunar_date.toSolarDate()

    return (solar_date - date_now).days

def argument_parser():
    parser = argparse.ArgumentParser()
    parser.add_argument('-s', '--subject',      help='the subject of mail',            required=True)
    parser.add_argument('-F', '--FROM',         help='where is the mail from',         required=True)
    parser.add_argument('-t', '--to',           help='where is the mail send to',      required=True, action='append')
    #parser.add_argument('-C', '--CONTENT',      help='the content of the mail',        required=True)
    parser.add_argument('-a', '--attachment',   help='the attachments of the mail',    action='append', default=[])
    parser.add_argument('-S', '--SMTP-SERVER',  help='the smtp server',                default='smtpp.qq.com')
    parser.add_argument('-P', '--SMTP-PORT',    help='the smtp port',                  type=int, default=465)
    parser.add_argument('-p', '--password',     help='the password of sender',         required=True)
    parser.add_argument('-c', '--count',        help='the allowed count when failing', type=int, default=1)

    return parser.parse_args()

def main():
    args = argument_parser();
    print(args)
    #date_now = datetime.now().date()
    #lunar_now = LunarDate(date_now.year, date_now.month, date_now.day)
    #上海杨浦区
    localtion = "http://www.weather.com.cn/weather1d/" + "101021700" + ".shtml"
    # 宁波海曙区
    # localtion = "http://www.weather.com.cn/weather1d/" + "101210402" + ".shtml"
    data = get_information(localtion)
    data['meet_day'] = count_day("2023-07-29")
    data['love_day'] = count_day("2023-09-22")
    data['girl_birthday'] = count_birthday(7,5)
    data['boy_birthday'] = count_birthday(8,8)
    data['day_message'] = get_daily_love()
    #data['date_time'] = str(date_now.year)+'年'+str(date_now.day) +'月'+str(date_now.day)+'日 ' + date_now.strftime("%A") +'\n农历 ' + str(lunar_now.year) + '年' +str(lunar_now.day) +'月'+str(lunar_now.day)+'日'

    message = '''
🌍城市：{city}
⛅天气：{weather}
🔆🌜温度：{temp}
🎎穿衣指数：{wear}
😷感冒指数：{feeling}
🏂运动指数: {sport}
🔅紫外线指数: {sun}
💓今天是我们认识的第{meet_day}天
💓今天是我们恋爱的第{love_day}天
🎂距离宝宝的生日还有{girl_birthday}天
🎂距离我的生日还有{boy_birthday}天

💌{day_message}
    '''.format(**data)
    print(message)

    sleep_time = 0
    for count in range(0, args.count, 1):
    # server | port | FROM | password | subject | to | content | attachment |
        time.sleep(sleep_time)
        ret = send_mail(server=args.SMTP_SERVER, port=args.SMTP_PORT, FROM=args.FROM, password=args.password, subject=args.subject, to=args.to, content=message, attachment=args.attachment)
        if ret:
            break
        else :
            sleep_time = count * count

# python send_mail.py -s "早安"  -F "zgamecdkey@moonton.com" -t "191130863@qq.com" -S "smtp.feishu.cn" -p "fRTpJXOxwBWlydDx"
if __name__ == '__main__' :
    main()


